from django.conf import settings
from django.db import models
from django.db.models import get_model
from django.utils.datastructures import SortedDict

def grouped(qs, context, params, extra_attr=None):
    groups = SortedDict()
    for item in qs(context, params):
        # Create a string key identifying unique scope for the item
        key = item.condition + (item.compress and 'C' or 'c')
        if extra_attr:
            key += getattr(item, extra_attr)
        if item.combine is False:
            key += item.path

        # Group items according to key (all items with same key can be grouped)
        if groups.has_key(key):
            groups[key]['assets'].append(item)
        else:
            groups[key] = {
                'assets': [item],
                'compress': item.compress,
                }
            if extra_attr:
                groups[key][extra_attr] = getattr(item, extra_attr)

    return groups.values()

class AssetQuerySet(models.query.QuerySet):
    def in_site(self):
        return self.filter(sites__id__exact=settings.SITE_ID)

    def used_for(self, context, params):
        return [a for a in self.in_site() if a.guard(context, params)]

class CSSQuerySet(AssetQuerySet):
    def grouped(self, context, params):
        return grouped(self.used_for, context, params, 'media')

class JSQuerySet(AssetQuerySet):
    def grouped(self, context, params):
        return grouped(self.used_for, context, params)

class CSSManager(models.Manager):
    def get_query_set(self): 
        model = get_model('farstyle', 'css')
        return CSSQuerySet(model)

    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            return getattr(self.get_query_set(), attr, *args)

class JSManager(models.Manager):
    def get_query_set(self): 
        model = get_model('farstyle', 'js')
        return JSQuerySet(model)

    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            return getattr(self.get_query_set(), attr, *args)

# class CombineManager(models.Manager):
#     def get_active(self, assets):
#         assets = ' '.join([a.path for a in assets])
#         return self.get_query_set().filter(assets=assets, obsolete=False)
# 
#     def combine(self, assets, type, context, param=None):
#         for old in self.get_active(assets):
#             old.expire()
#         data = '\n'.join([ asset.render(context) for asset in assets ])
#         c = self.create(assets=' '.join([a.path for a in assets]), type=type, param=param)
#         return c

__all__ = ['CSSManager', 'JSManager']
